package com.hmdp.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;

import static com.hmdp.utils.RedisConstants.CACHE_SHOP_TYPE_KEY;
import static com.hmdp.utils.RedisConstants.LOCK_SHOP_KEY;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    //引入缓存

    @Resource
    StringRedisTemplate stringRedisTemplate;


    @Override
    public List<ShopType> queryTypeList() {
        String key=CACHE_SHOP_TYPE_KEY;
        //1.从redis中查询缓存数据
        String shopTypeJson = stringRedisTemplate.opsForValue().get(key);
        //2.若存在，则直接返回
        if (StrUtil.isNotBlank(shopTypeJson)){
            return JSONUtil.toList(shopTypeJson, ShopType.class);
        }
        //3.不存在，从数据库中查询
        List<ShopType> shopTypeList =  query().orderByAsc("sort").list();
        //4.若不存在，返回错误
        if (shopTypeList.isEmpty()){
          //返回空的信息
            return Collections.emptyList();
        }
        //5.若存在，先将信息写入redis缓存当中
        stringRedisTemplate.opsForValue().set(key,JSONUtil.toJsonStr(shopTypeList));
        //6.返回数据信息。

        return shopTypeList;
    }
}
